<?php
class OffinvoicesController extends AppController {

	var $name = 'Offinvoices';
	var $uses = array('Invoice','Member');
	var $helpers = array('Html','Javascript','Ajax','Form');
	function index() {
		$this->Invoice->recursive = 0;		
		$this->paginate = array('conditions'=>array('Invoice.type'=>1),'order'=>'Invoice.id  DESC','limit' =>20 );
        $invoices = $this->paginate('Invoice');
		$this->set('invoices',$invoices);
	}
	function view($id=null) {
		if(!$id){
			$name=$_SERVER['HTTP_REFERER'];
			$this->redirect($name);
		}else{
			$this->data=$this->Invoice->read(null,$id);
			//Thông tin nhà phân phối
				$idMember=$this->Invoice->findById($id);
				$this->set('members',$this->Member->findById($idMember['Invoice']['id_user']));
		}

	}
	function closes($id=null) {
		if(!$id){
			$this->redirect($_SERVER['HTTP_REFERER']);
		}else{
			$close=array('Invoice'=>array(
									 'id'=>$id,
									 'status'=>'0'
									));
			if($this->Invoice->save($close)){
				$this->redirect('index');
			}						
		}

	}
	
	function actives($id=null) {
		if(!$id){
			$this->redirect($_SERVER['HTTP_REFERER']);
		}else{
			$active=array('Invoice'=>array(
										'id'=>$id,
										'status'=>1	
										));
			if($this->Invoice->save($active)){
				$this->redirect('index');
			}
		}
		

	}
	// them moi 
	function add() {
		if(!empty($this->data)){
			$this->Invoice->create();
			// kiem tra ton tai nha phan phoi qua tai khoan dang nhap va ma hoa don thong qua ma hoa don
			$checkUser=$this->Member->findByUser($this->data['Invoice']['id_user']);
			$checkInvoice=$this->Invoice->find('all',array('conditions'=>array(
																				'Invoice.code'=>$this->data['Invoice']['code'],
																				'Invoice.type'=>1
																				)));
			if($checkUser && count($checkInvoice)==0){
				$day=date('Y-m-d', strtotime($this->data['Invoice']['day']));
				$addInvoice=array('Invoice'=>array(
													'id_user'=>$checkUser['Member']['id'],
													'name'=>$checkUser['Member']['name'],
													'type'=>1,
													'code'=>$this->data['Invoice']['code'],
													'invoice_date'=>$day,
													'interpretation'=>$this->data['Invoice']['interpretation'],
													'total_money'=>$this->data['Invoice']['total_money'],
													'status'=>$this->data['Invoice']['status']
													));
				if($this->Invoice->save($addInvoice)){
					$this->redirect('index');
				}				
			}else{
				$this->redirect($_SERVER['HTTP_REFERER']);
			}
		}

	}
	//sua hoa don nhap vao 
	function edit($id=null) {
		
			if(!empty($this->data)){
				//kiem tra tai khoan co dung khong
				$checkUser=$this->Member->findByUser($this->data['Invoice']['id_user']);
				if(!$checkUser){
					$this->redirect($_SERVER['HTTP_REFERER']);
				}else{
				$idMember=$checkUser['Member']['id'];
				$memberName=$checkUser['Member']['name'];	
				  $day=date('Y-m-d', strtotime($this->data['Invoice']['day']));
				  $edit=array('Invoice'=>array(
				 								'id'=>$this->data['Invoice']['id'],
												'code'=>$this->data['Invoice']['code'],
												'interpretation'=>$this->data['Invoice']['interpretation'],
												'total_money'=>$this->data['Invoice']['total_money'],
												'invoice_date'=>$this->data['Invoice']['day'],
												'type'=>'1',
												'id_user'=>$idMember,
												'name'=>$memberName
				 								));
												
				 if($this->Invoice->save($edit)){
				 	$this->redirect('index');
				 }
				}
				
			}
			if(empty($this->data)){
				$this->data=$this->Invoice->read(null,$id);
				//lay ten tai khoan
				$nameMember=$this->Member->findById($this->data['Invoice']['id_user']);
				$this->set('nameMember',$nameMember['Member']['user']);
						
			}
		
	}
//inport file csv hoa don
	
	function import(){
		//if($this->Session->read('adminId')){
		if($_FILES){
			if ($_FILES["file"]["type"] == "application/vnd.ms-excel" || $_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" )
		  {
		  if ($_FILES["file"]["error"] > 0)
		    {
		     echo "<script>alert('Return Code:".$_FILES["file"]["error"]."');</script>";
		    }
		  else
		    {	
		    if (file_exists("upload/filedb/" . $_FILES["file"]["name"]))
		      {
		      unlink("upload/filedb/" . $_FILES["file"]["name"]);
		      }
		      move_uploaded_file($_FILES["file"]["tmp_name"],"upload/filedb/" . $_FILES["file"]["name"]);
		      $this->Session->write('filecsv',DOMAIN. "/upload/filedb/" . $_FILES["file"]["name"]);
		       $this->Session->write('filename',$_FILES["file"]["name"]);
		      $this->redirect('dunp');
		    }
		  }
		else
		  {
		  echo "<script>alert('Kiểu file không đúng');</script>";
		  }
		}
	}
	//dump vao databese 
	
	
	function dunp() {
					require_once 'dump_db/PHPExcel/IOFactory.php';
					$insert_count = 0;
					$update_count = 0;
					$errors = array();
					mysql_query("SET NAMES utf8");
					$row = 1;
					$filecsv=$this->Session->read('filecsv');
					$filename=$this->Session->read('filename');
					
					$this->Session->delete('filecsv');
					$this->Session->delete('filename');	
					
					//die();
					if($filecsv=="") {
						$this->redirect('import');
					}
					$objPHPExcel = PHPExcel_IOFactory::load("upload/filedb/".$filename);
					if($objPHPExcel->getWorksheetIterator()){
					$i=0;
					
					foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
						if($i>0) break;
						//setlocale(LC_ALL, 'ja_JP');
						$worksheetTitle     = $worksheet->getTitle();
						$highestRow         = $worksheet->getHighestRow(); // e.g. 10
						$highestColumn      = $worksheet->getHighestColumn(); // e.g 'F'
						$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);	
						$nrColumns = ord($highestColumn) - 64;
					 	for ($row = 2; $row <= $highestRow; ++ $row) {
							for ($col = 0; $col < $highestColumnIndex; ++ $col) {
								$cell = $worksheet->getCellByColumnAndRow($col, $row);
								$val = $cell->getValue();	
								if($val=='') $val=" ";
								$data[$col]=$val;
								$arr_data[$row-2]=$data;
							}
							//pr($data);die();
							//kiem tra cac truong chong
							if( ($data[1]=='') && ($data[7]=='') && ($data[9]=='')){
								$errors[$row] = "Bạn hãy nhập đẩy đủ thông tin theo yêu cầu ";
							}
							//kiem tra so chung tu
						/*	$codeInvoice=$this->Invoice->findByCode($data[1]);
							if(!empty($codeInvoice)){
								$errors[$row] = "Số chứng từ đã tồn tại";
								continue;
							}
							*/
							// Kiểm tra sự tồn tại của nhà phân phối
							$idMember=$this->Member->findByUser($data[9]);
							if(empty($idMember)){
								$errors[$row] = "Không tồn tại nhà phân phối";
								continue;							
							}else{
								$id_user[$row]=$idMember['Member']['id'];
								$name[$row]=$idMember['Member']['name'];
							}
							
							$insert[$row]=array('Invoice'=>array(
															'name'=>$name[$row],
															'id_user'=>$id_user[$row],
															'code'=>$data[1],
															'interpretation'=>$data[5],
															'total_money'=>$data[7],
															'invoice_date'=>$data[2],
															'type'=>1,
															'status'=>1
															));	
																				
						}
						
						}
						
						$this->set('errors', $errors);
						if(!$errors){
							$this->Invoice->saveall($insert);
							$this->redirect('index');
						}
						
						} 

	}
	
	
	// kiểm tra tồn tại của nhà phân phối
	function ck_user() {
		$this->layout= 'ajax';
		$user=$this->Member->findByUser($_GET['user']);
		if($user){
			echo "<span style='color:#0B55C4;'>Tài khoản hợp lệ </span>";
		}else{
			 
			echo "<span style='color:#FF0000;'>Tài khoản không tồn tại ! Xin vui lòng nhập lại </span>";
		}

	}
	// Kiem tra ma hoa don 
	function ck_code() {
		$this->layout= 'ajax';
		$code=$this->Invoice->find('all',array('conditions'=>array('Invoice.type'=>1,'Invoice.code'=>$_GET['invoiceCode'])));
		//pr($code);die();
		if(count($code)>0){
			echo "<span style='color:#FF0000;'>Mã hóa đơn đã tồn tại ! Xin vui lòng nhập lại ! </span>";
		}else{
			 
			echo "<span style='color:#0B55C4;'>Mã hóa đơn hợp lệ </span>";
		}


	}



}
?>